import {ipcRenderer} from 'electron';

import {IView} from '../types/IView';
import {IViewObject} from './IViewObject';

import divViewObject from './DivViewObject';
import hoverEffectPaneViewObject from './HoverEffectPaneViewObject';
import tabPaneViewObject from './TabPaneViewObject';
import tabItemViewObject from './TabItemViewObject';
import sliderPaneViewObject from './SliderPaneViewObject';
import sliderItemViewObject from './SliderItemViewObject';
import textViewObject from './TextViewObject';
import imageViewObject from './ImageViewObject';
import linkViewObject from './LinkViewObject';
import customViewObject from './CustomViewObject';

const viewObjectArray = [
  divViewObject,
  hoverEffectPaneViewObject,
  tabPaneViewObject,
  tabItemViewObject,
  sliderPaneViewObject,
  sliderItemViewObject,
  textViewObject,
  imageViewObject,
  linkViewObject,
  customViewObject
];

export interface ViewObjects {
  [name: string]: IViewObject<IView>;
}

const viewObjects: ViewObjects = {};

const customViews: {
  [name: string]: IView;
} = {};

viewObjectArray.forEach(viewObject => {
  viewObjects[viewObject.viewType] = viewObject;
});

ipcRenderer.on('load-views', (event, views) => {
  if (!views || views.length === 0) {
    return;
  }

  views.forEach(view => {
    customViews[view.name] = view.view;
  });
});

export function createView(viewType: string, designId: string): IView | null {
  const viewObject = viewObjects[viewType];
  if (viewObject) {
    return viewObject.create(designId);
  }

  if (customViews[viewType]) {
    return viewObjects.custom.create(designId, customViews[viewType]);
  }

  return null;
}

export function acceptView(viewType: string, childViewType: string): boolean {
  const viewObject = viewObjects[viewType];
  if (viewObject) {
    return viewObject.accept(childViewType);
  }
  return false;
}

export function preventDeleteChild(viewType: string, childViewIndex: number): boolean {
  const viewObject = viewObjects[viewType];
  if (viewObject) {
    return viewObject.preventDeleteChild(childViewIndex);
  }
  return false;
}

export default viewObjects;
